<?php
// +----------------------------------------------------------------------
// | Description: Api基础类，验证权限 (将前后台请求分流)
// +----------------------------------------------------------------------
// | Author: dongpeng
// +----------------------------------------------------------------------

namespace app\common\controller;

use app\common\adapter\AuthAdapter;
use think\Db;
use think\Request;
use \Firebase\JWT\JWT;

class ApiCommon extends Common
{
    protected $isClient = false; // 该访问是否来自客户端
    protected $header;
    protected $ApierrorMsg;

    public function _initialize()
    {
        parent::_initialize();
        $this->header = Request::instance()->header();
        // if (config('app_debug')) {
        //     $this->front();
        //     return;
        // }

        // 不需要验证的白名单
        $whiteList = [
            'Upload'    => [
                'index'
            ],
            'Products' => [
                'index',
                'read'
            ],
            'Brands' => [
                'index',
                'read'
            ],
            'BrandsSeries' => [
                'index',
                'read'
            ],
            'Categories' => [
                'index',
                'read'
            ],
            'ProductAttrs' => [
                'index',
                'read'
            ],
            'ProductImgs' => [
                'index',
                'read'
            ],
            'Skus' => [
                'index',
                'read'
            ],
            'SkuItems' => [
                'index',
                'read'
            ],
            'Comments' => [
                'index',
                'read'
            ],
            'OrderPays'  =>  [
                'wechatNotify'
            ],
            'Banners'  =>  [
                'index',
                'read'
            ]
        ];
        $c = request()->controller();
        $a = request()->action();
        if (array_key_exists($c, $whiteList)) {
            if (in_array($a, $whiteList[$c])) {
        // p(1212121);
                return; // 在白名单中不需要验证
            }
        }

        if ($this->header['authorization']) { // 存在该鉴权字段则为客户端鉴权
            // p(1);
            $this->front();
        } else {
            $this->back();
        }
    }

    /**
     * 客户端权限认证
     * @return void
     */
    public function front()
    {
        if (isset($this->header['authorization'])) {
            $key = config('jwt.key'); // 签名秘钥
            try {
                $this->header['authorization'] = $this->header['authorization'];
                $decoded = JWT::decode($this->header['authorization'], $key, array('HS256'));
            } catch (\Exception $e) {
                $this->abort(false, '鉴权失败!', 403);
            }

            $this->expire($decoded);
            $this->param['UserId'] = $decoded->UserId;

            // 检查改用户是否被拉黑
            $res = Db::table('shop_members') -> where(['Id' => $this->param['UserId'], 'Enabled' => 1]) -> find();
            $this->abort($res, '账户被冻结', 101);

            $this->isClient = true; // 权限验证通过 标注该访问为客户端
        }
    }

    public function back()
    {
        /*获取头部信息*/
        $authKey = $this->header['authkey'];
        $sessionId = $this->header['sessionid'];
        $cache = cache('Auth_' . $authKey);

        $this->abort(!empty($sessionId) and !empty($authKey) and !empty($cache), '登录已失效', 101);
        // if(empty($sessionId) or empty($authKey) or empty($cache)){
        //     // 校验sessionid和authKey
        //     $this -> ApierrorMsg = '服务端登录已失效';
        //     $this -> ApierrorCode = 101;
        //     return false;
        // }

        // 检查账号有效性
        $userInfo = $cache['userInfo'];
        $map['id'] = $userInfo['id'];
        $map['status'] = 1;

        $this->abort(Db::name('admin_user')->where($map)->value('id'), '账号已被删除或禁用', 102);
        // if(!Db::name('admin_user')->where($map)->value('id')){
        //     // 校验sessionid和authKey
        //     $this -> ApierrorMsg = '账号已被删除或禁用';
        //     $this -> ApierrorCode = 102;
        //     return false;
        // }

        // 更新缓存
        $this->MylogData['uid'] = $userInfo['id'];
        cache('Auth_' . $authKey, $cache, config('LOGIN_SESSION_VALID'));
        $authAdapter = new AuthAdapter($authKey);
        $request = Request::instance();
        $ruleName = $request->module() . '-' . $request->controller() . '-' . $request->action();

        $this->abort($authAdapter->checkLogin($ruleName, $cache['userInfo']['id']), '权限不足', 103);
        // if(!$authAdapter->checkLogin($ruleName, $cache['userInfo']['id'])){
        //     // 校验sessionid和authKey
        //     $this -> ApierrorMsg = '权限不足';
        //     $this -> ApierrorCode = 103;
        //     return false;
        // }
        $GLOBALS['userInfo'] = $userInfo;
    }

    /**
     * 检验token值是否过期
     *
     * @return void
     */
    public function expire()
    {
        return true;
    }
}
